<!--
 * @Author: your name
 * @Date: 2020-05-13 17:08:54
 * @LastEditTime: 2020-05-20 14:29:47
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \v1.0.0\components\kmlc-com\kmlc-file-manage\kmlc-file-manage.vue
 -->
<template>
  <view class="container" v-show="boxIsShow">
    <view class="tui-mtop fixed">
      <tui-tui-tabs :tabs="navbar" :currentTab="currentTab" @change="change" itemWidth="33.33%"></tui-tui-tabs>
    </view>
    <view class="cont">
      <radio-group v-if="showRadio" @change="fileChangeHanlder">
        <label
          class="uni-list-cell uni-list-cell-pd"
          v-for="(item, index) in navbar[currentTab].list"
          :key="index"
        >
          <view>
            <radio :value="item.filePath" :checked="index === navbar[currentTab].current" />
          </view>
          <view>{{item.name}}</view>
        </label>
      </radio-group>
      <tui-list-view v-else>
        <tui-list-cell
          v-for="(item,index) in navbar[currentTab].list"
          :key="index"
          @click="fileClickHanlder($event,index)"
        >
          <text class="tui-list-cell-name">{{item.name}}</text>
        </tui-list-cell>
      </tui-list-view>
    </view>
    <!-- <tui-modal ref="modal" @cancel="hideModal" :custom="true">
      <view class="tui-modal-custom">
        <video ref="video" src class="video"></video>
        <tui-button type="danger" shape="circle" @click="hideModal">确定</tui-button>
      </view>
    </tui-modal>-->
  </view>
</template>


<script>
export default {
  props: {
    showRadio: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      boxIsShow: false,
      navbar: [
        {
          name: "应用内文件",
          list: [],
          current: null
        },
        {
          name: "微信文件",
          list: [],
          current: null
        },
        //\.(mp3|wav|wma|ogg|ape|acc)
        {
          name: "QQ文件",
          list: [],
          current: null
        }
      ],
      currentTab: 0,
      picReg: /\.(gif|jpg|jpeg|bmp|png)/,
      videoReg: /\.(swf|flv|mp4|rmvb|avi|mpeg|ra|ram|mov|wmv)/,
      audioReg: /\.(mp3|wav|wma|ogg|ape|acc)/,
      officeReg: /\.(xls|xl|xla|xlt|xlm|xlc|xlw|doc|docx|ppt|pptx|pps|pot|ppa)/
    };
  },
  mounted() {
    this.getSaveFileList();
  },
  methods: {
    getSaveFileList() {
      let _this = this;
      // #ifdef APP-PLUS
      //应用内文件
      uni.getSavedFileList({
        success: function(res) {
          console.log(res.fileList);
          res.fileList.map(item => {
            let temp = item.filePath.split("/");
            item.name = temp[temp.length - 1];
            if (
              _this.picReg.test(item.name) ||
              _this.videoReg.test(item.name) ||
              _this.audioReg.test(item.name) ||
              _this.officeReg.test(item.name)
            ) {
              _this.navbar[0].list.push(item);
            }
          });
        }
      });
      //微信接收的文件
      plus.io.resolveLocalFileSystemURL(
        "/storage/emulated/0/tencent/MicroMsg/Download",
        function(entry) {
          let directoryReader = entry.createReader();
          directoryReader.readEntries(
            function(directoryEntry) {
              for (let index = 0; index < directoryEntry.length; index++) {
                const element = directoryEntry[index];
                if (
                  _this.picReg.test(element.name) ||
                  _this.videoReg.test(element.name) ||
                  _this.audioReg.test(element.name) ||
                  _this.officeReg.test(element.name)
                ) {
                  _this.navbar[1].list.push(element);
                  // _this.copyTo(element);
                  _this.copyTo2(element.toLocalURL());
                  // _this.saveFile(element.toLocalURL());
                }
              }
            },
            function(err) {
              console.log("Resolve file URL failed2ssss: " + e.message);
            }
          );
        },
        function(e) {
          console.log("Resolve file URL failed: " + e.message);
        }
      );

      //QQ接收的文件
      plus.io.resolveLocalFileSystemURL(
        "/storage/emulated/0/tencent/QQfile_recv",

        function(entry) {
          let directoryReader = entry.createReader();
          directoryReader.readEntries(
            function(directoryEntry) {
              for (let index = 0; index < directoryEntry.length; index++) {
                const element = directoryEntry[index];
                if (
                  _this.picReg.test(element.name) ||
                  _this.videoReg.test(element.name) ||
                  _this.audioReg.test(element.name) ||
                  _this.officeReg.test(element.name)
                ) {
                  _this.navbar[2].list.push(element);
                }
              }
            },
            function(err) {
              console.log("Resolve file URL failed2ssss: " + e.message);
            }
          );
        },
        function(e) {
          console.log("Resolve file URL failed: " + e.message);
        }
      );
      // #endif

      // #ifdef H5
      // uni.chooseFile()
      // #endif
    },
    initNavData() {
      for (let index2 = 0; index2 < this.fileList.length; index2++) {
        const element2 = this.fileList[index2];
        if (this.navbar[0].reg && this.navbar[0].reg.test(element2.name)) {
          element2.group = this.navbar[0].name;
          !this.navbar[0].list ? (this.navbar[0].list = []) : null;
          this.navbar[0].list.push(element2);
          continue;
        } else if (
          this.navbar[1].reg &&
          this.navbar[1].reg.test(element2.name)
        ) {
          element2.group = this.navbar[1].name;
          !this.navbar[1].list ? (this.navbar[1].list = []) : null;
          this.navbar[1].list.push(element2);
          continue;
        } else {
          !this.navbar[2].list ? (this.navbar[2].list = []) : null;
          this.navbar[2].list.push(element2);
          continue;
        }
      }
    },
    chooseFile() {
      return uni.getFileSystemManager();
    },
    change(e) {
      this.currentTab = e.index;
    },
    showBox() {
      this.boxIsShow = !this.boxIsShow;
    },
    fileChangeHanlder(evt) {
      console.log(evt.detail.value);
      for (let i = 0; i < this.navbar[this.currentTab].list.length; i++) {
        if (this.navbar[this.currentTab].list[i].value === evt.detail.value) {
          this.navbar[this.currentTab].current = i;
          break;
        }
      }
    },
    fileClickHanlder(evt, index) {
      console.log(evt, index);
      let temp = this.navbar[this.currentTab].list[index];
      !this.currentTab && console.log(JSON.stringify(temp));
      this.currentTab &&
        console.log(
          temp.toLocalURL() +
            "=====toRemoteURL:" +
            temp.toRemoteURL() +
            "====:" +
            temp.toURL()
        );
      console.log(temp.fullPath);
      let localPath = this.currentTab
        ? plus.io.convertAbsoluteFileSystem(temp.fullPath)
        : temp.filePath;
      console.log(localPath);
      if (this.picReg.test(temp.name)) {
        uni.previewImage({
          current: 0,
          urls: [localPath]
        });
      } else if (this.officeReg.test(temp.name)) {
        if (this.currentTab) {
          let tempUrl = temp.toRemoteURL();
          console.log("tempUrl:", tempUrl);
          uni.downloadFile({
            url: tempUrl,
            success: function(res) {
              console.log("tempFilePath:", res.tempFilePath);
              var filePath = res.tempFilePath;
              uni.saveFile({
                tempFilePath: filePath,
                success: function(res) {
                  var savedFilePath = res.savedFilePath;
                  uni.openDocument({
                    filePath: res.savedFilePath,
                    success: function(res) {
                      console.log("打开文档成功");
                    }
                  });
                }
              });
            }
          });
        } else {
          uni.openDocument({
            filePath: localPath,
            success: function(res) {
              console.log("打开文档成功");
            }
          });
        }
      } else {
        uni.showToast({
          icon: "none",
          title: "不支持预览"
        });
      }
    },
    hideModal() {
      this.$ref.modal.show = false;
    },
    copyTo(file) {
      
      var temp = file.name && file.name.split(".");
      var ext = "." + temp[temp.length - 1];
      var GName = this.generateID() + ext;
      console.log("GName:",GName);
      plus.io.requestFileSystem(
        plus.io.PRIVATE_DOC,
        function(fs) {
          // 可通过fs进行文件操作
          console.log("File system name: " + fs.name);
          // 通过fs.root获取DirectoryEntry对象进行操作
          // fs.root
           
          file.copyTo(
            fs.root,
            GName,
            function(res) {
              console.log("移动成功", JSON.stringify(res));
            },
            function(err) {
              console.log("移动失败:", JSON.stringify(err));
            }
          );
        },
        function(err) {
          console.log("Request file system failed: " + JSON.stringify(err));
        }
      );
    },
    copyTo2(path) {
      var temp = path && path.split(".");
      var ext = "." + temp[temp.length - 1];
      var GName = this.generateID() + ext;
          console.log(GName);
      plus.io.resolveLocalFileSystemURL(path, function(entry) {
        console.log(entry.fullPath);
        plus.io.resolveLocalFileSystemURL('_doc/', function(file) {
          entry.copyTo(
            file,
            GName,
            function(entry) {
              console.log("New Path: " + entry.fullPath);
              uni.openDocument({
                filePath: entry.fullPath,
                success: function(res) {
                  console.log("打开文档成功");
                }
              });
            },
            function(e) {
              console.log("错1误" + JSON.stringify(e));
            }
          );
        },
        function(err) {
          console.log("resolveLocalFileSystemURL222: " + JSON.stringify(err));
        });
      });
    },
    generateID() {
      return Math.random()
        .toString(36)
        .substr(2);
    },
    saveFile(path){
      uni.saveFile({
        tempFilePath: path,
        success: function (res) {
          console.log('新路径：',res.savedFilePath);
        }
      });
    }
  }
};
</script>


<style lang="scss">
.container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99;
  background: #fff;
  overflow-y: auto;
  .cont {
    padding-top: 36px;
  }
  .fixed {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    z-index: 100;
  }
}

.tui-list-cell-name {
  padding-left: 20upx;
  vertical-align: middle;
  line-height: 30upx;
}
</style>